package com.czd.support.util;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class ObjectUtil {

	/**
	 * 检查是否存在方法
	 * 
	 * @param methods
	 * @param methodName
	 * @return
	 */
	private static boolean existMethod(Method[] methods, String methodName) {
		for (Method method : methods) {
			if (method.getName().equals(methodName))
				return true;
		}
		return false;
	}

	/**
	 * 获得方法名
	 * 
	 * @param in
	 * @return
	 */
	private static String upperHeadChar(String in) {
		return in.substring(0, 1).toUpperCase() + in.substring(1);
	}

	/**
	 * 拷贝父类属性到子类
	 * @param father
	 * @param child
	 * @return
	 * @throws Exception
	 */
	public static Object copyFatherToChild(Object father, Object child)
			throws Exception {
		Class<?> c = child.getClass().getSuperclass();
		do {
			if (c == father.getClass()) {
				Class<?> fatherClass = father.getClass();
				Field ff[] = fatherClass.getDeclaredFields();
				String g = null;
				String s = null;
				for (int i = 0; i < ff.length; i++) {
					Field f = ff[i];// 取出每一个属性，如deleteDate
					g = "get" + upperHeadChar(f.getName());
					s = "set" + upperHeadChar(f.getName());
					if (existMethod(fatherClass.getMethods(), g)) {
						Method m = fatherClass.getMethod(g);
						if (existMethod(fatherClass.getMethods(), s)){
							f.setAccessible(true);
							f.set(child, m.invoke(father));
						}
					}
				}
				return child;
			} else
				c = c.getSuperclass();
		} while ((Class<?>) c != Object.class);
		throw new Exception("target is not my child.");
	}
}
